<?php
// 如：db:seed 或者 清空数据库命令的地方调用

/**
 * 递归创建目录
 *
 * 与 mkdir 不同之处在于支持一次性多级创建, 比如 /dir/sub/dir/
 *
 * @param  string
 * @param  int
 * @return boolean
 */
function make_dir($dir, $permission = 0777)
{
    return @mkdir($dir, $permission, true);
}

/**
 * 获取缓存的key的完整结构
 * @param $key
 * @return string
 */
function getCacheKey($key)
{
    return config('redis_key.run_model') . config($key);
}

function getAppBasePath(){
    return str_replace('\\','/',realpath(dirname(__FILE__).'/../'))."/";
}

function getBasePath(){
    return str_replace('\\','/',realpath(dirname(__FILE__).'/../../'))."/";
}

function redirectToUrl($url){
    header("Location:".$url);
}

/*
 * 获取用户IP的函数
 */
function getIp(){
    $onlineip = "";
    if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
        $onlineip = getenv('HTTP_CLIENT_IP');
    } elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
        $onlineip = getenv('HTTP_X_FORWARDED_FOR');
    } elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
        $onlineip = getenv('REMOTE_ADDR');
    } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
        $onlineip = $_SERVER['REMOTE_ADDR'];
    }
    return $onlineip;
}

function getDomain(){
    return config('app.app_domain');
}

function getUploadUrl(){
    return getDomain().'/upload/';
}

function getUploadDir(){
    return base_path().'/public/upload/';
}

function getPublicDir(){
    return base_path().'/public/';
}

function getImageBaseUrl(){
    return getDomain().'/';
}

/**
 *替换特殊字符以及空格
 * @param $strParam
 * @return mixed
 */
function replaceSpecialChar($strParam){
    $regex = "/\/|\~|\!|\@|\#|\\$|\%|\^|\&|\*|\(|\)|\_|\+|\{|\}|\:|\<|\>|\?|\[|\]|\,|\.|\/|\;|\'|\`|\-|\=|\\\|\|/";
    $str =  preg_replace($regex,"",$strParam);

    $search = array(" ","　","\n","\r","\t");
    $replace = array("","","","","");
    return str_replace($search, $replace, $str);
}

/**
 * 过滤emoji
 * @param $str
 * @param string $replace
 * @return mixed
 */
function filter_emoji($str,$replace="") {
    $regex = '/(\\\u[ed][0-9a-f]{3})/i';
    $str = json_encode($str);
    $str = preg_replace($regex, $replace, $str);
    return json_decode($str);
}

/**
 * 二维数组按照某个字段排序
 * @param $arr
 * @param $column
 * @param string $sortType
 * @return mixed
 */
function sortArr($arr, $column, $sortType = 'asc')
{
    $sortType = $sortType == 'asc' ? SORT_ASC : SORT_DESC;
    $sortColumnValues = array_column($arr, $column);
    array_multisort($sortColumnValues, $sortType, $arr);
    return $arr;
}

/**
 * 格式化数组的数据
 * @param $arr
 * @param $key
 * @param string $default
 * @return mixed
 */
function formatArrValue($arr, $key, $default = ""){
    return isset($arr[$key]) ? $arr[$key] : $default;
}
